const express = require('express');
const article = express.Router();
// const multer = require('multer')
// const fs = require('fs')
const formidable = require('formidable');
const path = require('path')
const { Article } = require('../model/article');

article.get('/', async (req, res) => {
    let query = req.query.query
    let pagesize = parseInt(req.query.pagesize)
    let pagenum = parseInt(req.query.pagenum)
    let start = (pagenum - 1) * pagesize;
    let reg = new RegExp('.*' + query + '.*$')
    let articles = await Article.find({ "title": { $regex: reg, $options: 'i' } }).limit(pagesize).skip(start).populate('author');
    if (!articles) {
        return res.sendResult(null, 400, "没有搜索到文章");
    } else {
        let count = await Article.find({ "title": { $regex: reg, $options: 'i' } }).countDocuments();
        let data = {};
        data.articles = articles;
        data.total = count;
        return res.sendResult(data, 200, "获取成功");
    }
})
//置顶设置
article.put('/:id/state/:state', async (req, res) => {
    let change = await Article.updateOne({ _id: req.params.id }, {
        isTop: req.params.state
    });
    if (!change) {
        return res.sendResult(null, 400, "修改失败");
    } else {
        return res.sendResult(null, 200, "状态设置成功");
    }
})
//删除文章
article.delete("/:id", async (req, res) => {
    await Article.findOneAndDelete({ _id: req.params.id });
    res.sendResult(null, 200, "删除成功");
})

//封面上传路径
// const imgURL = path.join(__dirname, '../', 'uploads');
// article.post(
//     "/upload",
//     multer({
//         //设置文件存储路径
//         dest: imgURL,
//     }).array("file", 1),
//     function (req, res, next) {
//         let files = req.files;
//         console.log(files);
//         let file = files[0];
//         let fileInfo = {};
//         let path = imgURL + "/" + Date.now().toString() + "_" + file.originalname;
//         fs.renameSync(imgURL + "/" + file.filename, path);
//         //获取文件基本信息
//         fileInfo.type = file.mimetype;
//         fileInfo.name = file.originalname;
//         fileInfo.size = file.size;
//         fileInfo.path = path;
//         return res.sendResult(fileInfo, 200, "上传成功")
//     }
// );
article.post('/', async (req, res) => {
    // 1.创建表单解析对象
    const form = new formidable.IncomingForm();
    // 2.配置上传文件的存放位置
    form.uploadDir = path.join(__dirname, '../', 'uploads');
    // 3.保留上传文件的后缀
    form.keepExtensions = true;
    // 4.解析表单
    form.parse(req, async (err, fields, files) => {
        // 1.err错误对象 如果表单解析失败 err里面存储错误信息 如果表单解析成功 err将会是null
        // 2.fields 对象类型 保存普通表单数据
        // 3.files 对象类型 保存了和上传文件相关的数据
        // res.send(files.cover.path.split('public')[1])
        await Article.create({
            title: fields.title,
            author: fields.author,
            isTop: fields.isTop,
            content: fields.content,
            catagories: fields.catagories,
            tags: fields.tags,
            cover: files.file.path.split('server')[1]
        });
        res.sendResult(files, 200, '发表成功');
    })
})

// 将路由对象做为模块成员进行导出
module.exports = article;
